package com.insnow.knowshare.service.impl;

import com.insnow.knowshare.entity.Post;
import com.insnow.knowshare.entity.PostDTO;
import com.insnow.knowshare.entity.User;
import com.insnow.knowshare.repository.AdminPostRepository;
import com.insnow.knowshare.repository.UserRepository;
import com.insnow.knowshare.repository.PostRepository;
import com.insnow.knowshare.repository.ReplyRepository;
import com.insnow.knowshare.service.AdminPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import com.insnow.knowshare.entity.UserActivityDTO;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.HashMap;

@Service
public class AdminPostServiceImpl implements AdminPostService {

    @Autowired
    private AdminPostRepository adminPostRepository;

    @Autowired  
    private UserRepository userRepository;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private ReplyRepository replyRepository;

    @Override
    public List<PostDTO> getAllPosts() {
        List<Post> posts = adminPostRepository.findAllByOrderByIsTopDescIdDesc();
        List<PostDTO> dtos = new ArrayList<>();
        for (Post post : posts) {
            PostDTO dto = PostDTO.fromEntity(post, userRepository.findById(post.getUserId()).orElse(null).getUsername());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public void setPostTop(Long id, boolean top) {
        Post post = adminPostRepository.findById(id).orElseThrow(() -> new RuntimeException("帖子不存在"));
        post.setIsTop(top);
        if (top) {
            post.setTopTime(new Date());
        } else {
            post.setTopTime(null);
        }
        adminPostRepository.save(post);
    }

    @Override
    public void deletePost(Long id) {
        Post post = adminPostRepository.findById(id).orElseThrow(() -> new RuntimeException("帖子不存在"));
        post.setIsDeleted(true);
        adminPostRepository.save(post);
    }

    @Override
    public void restorePost(Long id) {
        Post post = adminPostRepository.findById(id).orElseThrow(() -> new RuntimeException("帖子不存在"));
        post.setIsDeleted(false);
        adminPostRepository.save(post);
    }

    @Override
    public void updatePostStatus(Long id, int status) {
        Post post = adminPostRepository.findById(id).orElseThrow(() -> new RuntimeException("帖子不存在"));
        post.setStatus(status);
        adminPostRepository.save(post);
    }

    @Override
    public List<PostDTO> getPostsByStatus(int status) {
        List<Post> posts = adminPostRepository.findByStatusOrderByIsTopDescCreatedAtDesc(status);
        List<PostDTO> dtos = new ArrayList<>();
        for (Post post : posts) {
            PostDTO dto = PostDTO.fromEntity(post, userRepository.findById(post.getUserId()).orElse(null).getUsername());
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public Page<PostDTO> getPostsByStatusPaged(int status, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<Post> postPage = adminPostRepository.findByStatusOrderByIsTopDescTopTimeDescIdDesc(status, pageRequest);
        return postPage.map(post -> {
            PostDTO dto = PostDTO.fromEntity(post, userRepository.findById(post.getUserId()).orElse(null).getUsername());
            return dto;
        });
    }

    @Override
    public List<UserActivityDTO> getUserActivity(LocalDateTime start, LocalDateTime end) {
        // 1. 查所有用户
        List<Object[]> users = userRepository.findAllUserIdAndUsername();
        // 2. 查发帖数
        List<Object[]> postCounts = postRepository.countPostsByUser(start, end);
        // 3. 查回帖数
        List<Object[]> replyCounts = replyRepository.countRepliesByUser(start, end);

        // 4. 转为Map方便合并
        Map<Long, Long> postMap = new HashMap<>();
        for (Object[] arr : postCounts) {
            postMap.put((Long) arr[0], (Long) arr[1]);
        }
        Map<Long, Long> replyMap = new HashMap<>();
        for (Object[] arr : replyCounts) {
            replyMap.put((Long) arr[0], (Long) arr[1]);
        }

        // 5. 合并
        List<UserActivityDTO> result = new ArrayList<>();
        for (Object[] arr : users) {
            Long userId = (Long) arr[0];
            String username = (String) arr[1];
            Long postCount = postMap.getOrDefault(userId, 0L);
            Long replyCount = replyMap.getOrDefault(userId, 0L);
            result.add(new UserActivityDTO(userId, username, postCount, replyCount));
        }
        return result;
    }

    @Override
    public Map<String, Object> getUserActivityPaged(LocalDateTime start, LocalDateTime end, int page, int size) {
        List<UserActivityDTO> all = getUserActivity(start, end); // 原有统计方法
        // 排序
        all.sort((a, b) -> Long.compare(
            (b.getPostCount() == null ? 0 : b.getPostCount()) + (b.getReplyCount() == null ? 0 : b.getReplyCount()),
            (a.getPostCount() == null ? 0 : a.getPostCount()) + (a.getReplyCount() == null ? 0 : a.getReplyCount())
        ));
        int total = all.size();
        int from = Math.min(page * size, total);
        int to = Math.min(from + size, total);
        List<UserActivityDTO> records = all.subList(from, to);
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        return result;
    }
}